#!/usr/bin/env python

import os
import sys
import cStringIO

from base import BaseHandler
import xml.dom.minidom as dom

class CgiHandler(BaseHandler):
	""" Handles files that use CGI interface without being WSGI"""
	own_response = True
	headers = []
	def handle_start(self):
		if(not self.environ.has_key('renyare.config')):
			self._err("No config variable")
		scriptDir = self.environ['renyare.config']['local']['modules']['dynamic']
		newout = cStringIO.StringIO() # Create a new output buffer
		if(os.path.isfile(os.path.join(scriptDir, self.module+".py"))):
			try:
				oldpath = sys.path # Save system search paths
				oldout = sys.stdout # Save original stdout object
				sys.path.append(scriptDir) # Add the path to search
				sys.stdout = newout # Catch stdout from cgi script
				__import__(self.module) # Run the file
				sys.stdout = oldout # Return saved stdout...
				sys.path = oldpath # ...and path
			except:
				self._err("Error running cgi application")
		else:
			self._err("Error configuring cgi application")
		output = newout.getvalue().split("\n\n", 1) # Detect HTTP headers sent
		del(newout) # Remove non-split value
		if(len(output)>=2): # CGI script has to provide headers
			for i in output[0].split("\n"):
				hList = i.split(':')
				if(len(hList) >= 2):
					self.headers.append((hList[0], "".join(hList[1:])))
		else: self._err("No headers provided from cgi script")
		self.data = output[1]
		try:
			self.xml = dom.parseString(util.xmlify(self.data, self.module))
		except: None

	def own_response(self, status, headers):
		ok_status = "200 OK"
		self.start_response(ok_status, self.headers)
